<script setup>
import { ref, onMounted, reactive } from 'vue'
import { User } from '@/api'
let props = defineProps({
    modelValue: {
        type: String,
        required: true,
    },
    action: {
        type: String,
        default: 'http://www.shop.net/adminapi/file/upload'
    },
    pid: {
        type: String,
        default: '0'
    },
})
let headers = reactive({
    'Authori-zation': `Bearer ${sessionStorage.token}`
})
// 发射事件
let emit = defineEmits(['update:modelValue']);
// 关闭抽屉或者dialog时的回调，清除表单所有状态
let ref_form = ref(null)
let handleClose = (formName) => {
    if (!formName) return
    formName.resetFields()
}
// 加载图标
// 点击打开添加icon图标
let innerVisible = ref(false)
let handleIcon = () => {
    innerVisible.value = true;
    all_img_id.value.length = ''
    load_cate()
    load_icon()
}
let tab_cate = ref([])
//加载分类选项
let load_cate = async () => {
    let { data, status } = await User.getImageCate({ name: search_icon_cate.value })
    if (status) {
        tab_cate.value = data.list
        tab_cate.value.unshift({
            name: '全部图片',
            id: 0,
            pid:0
        })
    }
}
//加载所有icon图标
let all_icon = ref([])
let total = ref()
let load_icon = async () => {
    let { data, status } = await User.getImage({ pid: activeName.value, limit: pagesize.value, page: pageiconindex.value })
    if (status) {
        all_icon.value = data.list
        total.value = data.count
    }
}
//点击图标分页
let pageiconindex = ref(1)
let pagesize = ref(18)
let handlePage = (page) => {
    pageiconindex.value = page
    load_icon()
}
// 选择图片
// 点击图片获取他们的id
let all_img_id = ref([])
let is_found = ref("")
let handleImgId = (id, index) => {
    is_found.value = all_img_id.value.indexOf(id)
    if (is_found.value == -1) {
        all_img_id.value.push(id)
    } else {
        all_img_id.value.splice(is_found.value, 1)
    }
}
// 判断id是否在数组中
let is_select = (id) => {
    return all_img_id.value.includes(id)
}
// 使用图片
// 图标
let save_img = ref("")
let handleUseImg = () => {
    img_id.value = all_img_id.value.join(",")
    if (all_img_id.value.length > 1) {
        ElMessage.error('最多只能选一张图片')
        return;
    }
    all_icon.value.forEach((item) => {
        if (item.att_id == img_id.value) {
            save_img.value = item.att_dir
            emit('update:modelValue', save_img.value);
        }
    })
    innerVisible.value = false;
}
// 搜索icon图标的分类名称
let search_icon_cate = ref("")
let handleSearchIconCate = async () => {
    load_cate()
}
// 移动图片到其他的分类
let img_id = ref("")
let handleCateSelect = async (id) => {
    img_id.value = all_img_id.value.join(",")
    if (all_img_id.value.length < 1) {
        ElMessage.error('请先选择图片图片')
        return;
    }
    let { msg, data, status } = await User.do_move({ images: img_id.value, pid: id })
    if (status) {
        ElMessage.success(msg)
        load_icon()
    } else {
        ElMessage.error(msg)
    }
}
// 切换图标的分类tab栏
let activeName = ref(0)
let handleClick = (name) => {
    activeName.value = name.props.name
    load_icon()
}
// 删除icon图标
let handleRemoveImg = () => {
    img_id.value = all_img_id.value.join(",")
    ElMessageBox.confirm(`确定要删除选中的图片吗`, '提示', { type: 'warning' })
        .then(async () => {
            let { status, msg } = await User.remove_img({ ids: img_id.value })
            if (status == 200) {
                ElMessage.success(msg)
                all_img_id.value.length = ''
                img_id.value = ''
                load_icon()
            } else {
                ElMessage.error(msg)
            }
        })
        .catch(() => { ElMessage.info('取消成功！') })
}
// 上传本地图片
let handleUploadImg = async (res) => {
    let { status, msg, src } = res;
    if (status) {
        ElMessage.success(msg);
        all_img_id.value.length = ''
        load_icon()
    }
}
// 对图片的格式检查
let beforeAvatarUpload = (file) => {
    let reg = /^image\/(jpeg||png)$/;
    const isImage = reg.test(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isImage && isLt2M;
}
//上传失败
let handleUploadError = (err, file, fileList) => {
    let { status: statusCode, message } = err;
    switch (statusCode) {
        case 400:
            let { status, msg } = JSON.parse(message);
            ElMessage.error(msg);
            break;
        case 401:
            let { code } = JSON.parse(message);
            ElMessage.error(`错误代码:401.${code},请重新登录账户！`)
            break;
        default:
            break;
    }
}
</script>

<template>
    <!--点击框 -->
    <div class="avatar-content" @click="handleIcon">
        <el-icon v-if="modelValue===''">
            <Plus />
        </el-icon>
        <img :src="modelValue" alt="" class="use-icon" v-if="modelValue" style="width: 61px; height: 61px;">
    </div>
    <!-- 添加等级弹出框 -->
    <!-- 点击上传图片 -->
    <el-dialog v-model="innerVisible" width="63%" title="选择图标" append-to-body @close="handleClose(ref_form)">
        <el-form :inline="true" class="form-content" ref="ref_form" :model="all_icon">
            <div class="iocn-left">
                <div class="mt-4">
                    <el-form-item style="width:25%;">
                        <el-input v-model="search_icon_cate" placeholder="请输入分类名称" class="input-with-select">
                            <template #append>
                                <el-button icon="Search" type="primary" @click="handleSearchIconCate" />
                            </template>
                        </el-input>
                    </el-form-item>
                </div>
                <div class="icon-right">
                    <el-form-item>
                        <el-button :type="!all_img_id.length ? 'info' : 'primary'" :disabled="!all_img_id.length"
                            @click="handleUseImg">使用选中图片</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-upload class="upload-demo" :data="{ pid }" accept="image/*" :headers="headers"
                            :show-file-list="false" :action="action" :on-success="handleUploadImg"
                            :before-upload="beforeAvatarUpload" :on-error="handleUploadError">
                            <el-button type="primary">上传图片</el-button>
                        </el-upload>
                    </el-form-item>
                    <el-form-item>
                        <el-button :type="!all_img_id.length ? 'info' : 'danger'" :disabled="!all_img_id.length"
                            @click="handleRemoveImg">删除图片</el-button>
                    </el-form-item>
                    <el-select clearable v-model="tab_cate.id" class="m-2" placeholder="图片移动至" @change="handleCateSelect">
                        <el-option v-for="item in tab_cate" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </div>
                <el-tabs tab-position="left" style="height: 450px" v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane :label="item.name" v-for="item in  tab_cate " :key="item.id" :name="item.id">
                        <div class="all_icon">
                            <div v-for="(item, index) in  all_icon " :key="item.att_id" :label="item.real_name"
                                class="check_img">
                                <el-badge
                                    :value="all_img_id.indexOf(item.att_id) >= 0 ? all_img_id.indexOf(item.att_id) + 1 : ''"
                                    class="item">
                                    <img :src="item.att_dir" alt="" :title="item.real_name" class="img_border"
                                        @click="handleImgId(item.att_id, index)"
                                        :class="{ border: is_select(item.att_id) }">
                                </el-badge>
                                <p class="icon-title">{{ item.real_name }}</p>
                            </div>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-form>
        <el-pagination class="el-pagination2" background :total="total" @current-change="handlePage"
            :page-size="pagesize" />
    </el-dialog>
</template>

<style scoped lang="less">
.avatar-content {
    width: 61px;
    height: 61px;
    border: 1px solid #ddd;
    border-radius: 5px;
    text-align: center;
    line-height: 60px;
    box-shadow: 2px 2px 5px 1px #ddd;
    cursor: pointer;

    .use-icon {
        position: absolute;
        left: 1px;
        top: 1px;
        background-color: #fff;
        border-radius: 5px;
    }
}

.iocn-left {
    padding-right: 10px;
}

.icon-right {
    position: absolute;
    right: 20px;
    top: 80px;
    display: flex;
    justify-content: flex-start;
}

.all_icon {
    display: flex;
    flex-wrap: wrap;
    cursor: pointer;

    img {
        width: 100px;
        height: 100px;
    }

    .icon-title {
        width: 100px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
}

.check_img {
    padding: 8px;

}

.img_border {
    border: 2px solid #fff;
}

.border {
    border: 2px solid green;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.el-pagination2 {
    position: absolute;
    right: 20px;
    bottom: 20px;
}


.el-checkbox-button__inner {
    padding: 4px 8px;
    border: 0;
}
</style>